--[[
   create at 2019-03-01 18:41:38
   author:刘易周
   @brief:
--]]
require "kuru_wrap.lua"
require "makeup.lua"

-- 初始参数
faceContour = 0.0
cheek = 0.0
lip = 0.0
colorLens = 0.0
eyeBrow = 0.0
eyeShadow = 0.0
eyeLiner = 0.0
eyeLashes = 0.0
LUT_NAME = "lut.png"
lutStrength = 0
applyOnlyFilter = false

g_AniTime = 0
g_PreRes = nil
g_count = 1
AniPlay = false
g_time = 0
-- 静态按钮
buttonConfigEnd = {
  {
    path = "button/b_aa",
    type = 0,
    scale = 0.30,
    tx = -0.3,
    ty = 0.18,
    anchor = KuruBackgroundImageNodeAnchorType.CENTER,
    stretch = KuruBackgroundImageNodeStretch.UNIFORM_FILL,
    fps = 10,
    blendmode = BlendMode.Lighten
  },
  {
    path = "button/b_cc",
    type = 0,
    scale = 0.30,
    tx = 0,
    ty = 0.18,
    anchor = KuruBackgroundImageNodeAnchorType.CENTER,
    stretch = KuruBackgroundImageNodeStretch.UNIFORM_FILL,
    fps = 10,
    blendmode = BlendMode.Lighten
  },
  {
    path = "button/b_bb",
    type = 0,
    scale = 0.30,
    tx = 0.3,
    ty = 0.18,
    anchor = KuruBackgroundImageNodeAnchorType.CENTER,
    stretch = KuruBackgroundImageNodeStretch.UNIFORM_FILL,
    fps = 10,
    blendmode = BlendMode.Lighten
  }
}
-- 动态按钮
buttonConfigBegin = {
  {
    path = "button/b_aaa",
    type = 0,
    scale = 0.20,
    tx = -0.3,
    ty = 0.18,
    anchor = KuruBackgroundImageNodeAnchorType.CENTER,
    stretch = KuruBackgroundImageNodeStretch.UNIFORM_FILL,
    fps = 1,
    blendmode = BlendMode.Lighten
  },
  {
    path = "button/b_ccc",
    type = 0,
    scale = 0.20,
    tx = 0,
    ty = 0.18,
    anchor = KuruBackgroundImageNodeAnchorType.CENTER,
    stretch = KuruBackgroundImageNodeStretch.UNIFORM_FILL,
    fps = 1,
    blendmode = BlendMode.Lighten
  },
  {
    path = "button/b_bbb",
    type = 0,
    scale = 0.20,
    tx = 0.3,
    ty = 0.18,
    anchor = KuruBackgroundImageNodeAnchorType.CENTER,
    stretch = KuruBackgroundImageNodeStretch.UNIFORM_FILL,
    fps = 10,
    blendmode = BlendMode.Lighten
  }
}
eyeConfig = {
  {
    path = "img1/f_xin_0000.png",
    type = 1,
    scale = 0.30,
    tx = 0.05,
    ty = 0.34,
    anchor = KaleStickerNodeAnchorType.CENTER,
    location = KaleStickerNodeLocationType.EYE_LB,
    flip = false,
    fps = 20,
    blendmode = BlendMode.Multiply
  },
  {
    path = "img1/f_xin_0000.png",
    type = 1,
    scale = 0.30,
    tx = -0.05,
    ty = 0.34,
    anchor = KaleStickerNodeAnchorType.CENTER,
    location = KaleStickerNodeLocationType.EYE_RB,
    flip = false,
    fps = 20,
    blendmode = BlendMode.Multiply
  }
}
isBreakEffect = false
eyeNodes = {}
buttonBeginNodes = {}
buttonEndNodes = {}
buttoninit = false

function createNode(scene, config)
  local nodes = {}
  for i = 1, #config do
    nodes[i] = KuruWrap.addNodeWithConfig(scene, config[i])
  end
  return nodes
end

--call once when scene loaded
function initialize(scene)
  g_PreRes = scene:getResolution()
  local kuruEngineInstance = KuruEngine.getInstance()
  kuruFaceDetector = KuruFaceDetectorExtension.cast(kuruEngineInstance:getExtension("KuruFaceDetector"))
  kuruBody = KuruHumanActionExtension.cast(kuruEngineInstance:getExtension("KuruHumanAction"))
  scene:getInternalScene():setHandDetection(true)
  kuruTouch = KuruTouchExtension.cast(kuruEngineInstance:getExtension("KuruTouch"))
  kuruTouch:getTouchDownEvent():addEventHandler(onTouchDown)
  makeupLip = makeupinitialize(scene)
  filter1 =
    addNodeAndRelease(scene, KuruShaderFilterNode.createWithFragmentShaderFile(BASE_DIRECTORY .. "shaking.frag", true))
  filter2 =
    addNodeAndRelease(
    scene,
    KuruShaderFilterNode.createWithFragmentShaderFile(BASE_DIRECTORY .. "divergency.frag", true)
  )
  filter1:getMaterial():getParameter("time"):setFloat(g_time)
  filter2:getMaterial():getParameter("time"):setFloat(g_time)
  eyeNodes = createNode(scene, eyeConfig)
  eyeNodes[1]:setEnabled(false)
  eyeNodes[2]:setEnabled(false)

  -- snap = addNodeAndRelease(scene, KuruSnapshotNode.create())

  -- sampler1 = addNodeAndRelease(scene, KuruFrameBufferNode.create())
  -- sampler1:setFrameBufferScale(1, 1)
  -- addChildAndRelease(sampler1, KuruBackgroundImageNode.createFromSampler(snap:getSnapshot(), BlendMode.None))
  -- displayNode =
  --   addNodeAndRelease(
  --   scene,
  --   KuruShaderFilterNode.createWithFragmentShaderFile(BASE_DIRECTORY .. "passthrough.frag", true)
  -- )
  -- displayNode:setChannel0(sampler1:getSampler())

  
end
function playBreakEffect(scene, elapsedTime)
  g_time = g_time + elapsedTime / 1000 * 3
  if g_time >= 2.5 and g_time < 4.5 then
    if g_count == 1 then
      buttonEndNodes[1]:setEnabled(false)
      buttonBeginNodes[1]:setEnabled(false)
    elseif g_count == 2 then
      buttonEndNodes[2]:setEnabled(false)
      buttonBeginNodes[2]:setEnabled(false)
    elseif g_count == 3 then
      buttonEndNodes[3]:setEnabled(false)
      buttonBeginNodes[3]:setEnabled(false)
    end
  end
  if g_count == 1 or g_count == 3 then
    filter1:getMaterial():getParameter("time"):setFloat(g_time)
  elseif g_count == 2 then
    filter2:getMaterial():getParameter("time"):setFloat(g_time)
  end

  if g_time >= 4.5 then
    isBreakEffect = false
    g_time = 0
    changeMakeup()
  end
end
function changeMakeup()
  if g_count == 1 then
    eyeNodes[1]:setEnabled(true)
    eyeNodes[2]:setEnabled(true)
    changeParamEye()
  elseif g_count == 2 then
    changeParamBlush()
  elseif g_count == 3 then
    changeParamLip()
  end
end
--call every frame,elapsed time is the time elapsed this frame
function frameReady(scene, elapsedTime)
  -- 创建静态按钮
  if buttoninit==false then
  buttonBeginNodes = createNode(scene, buttonConfigBegin)
  buttoninit=true
  print("kuru创建按钮")
  end

  isTouched(scene, elapsedTime)
  makeupframeReady(scene, elapsedTime, makeupLip)

  if AniPlay then
    if isBreakEffect then
      playBreakEffect(scene, elapsedTime)
    else
      AniControl(scene, elapsedTime)
    end
  end
  if g_AniTime >= 1 then
    g_AniTime = 0
    AniPlay = false

    g_count = g_count + 1
  end
end
function AniControl(scene, elapsedTime)
  g_AniTime = elapsedTime / 1000 + g_AniTime
end
function isTouched(scene, elapsedTime)
  if kuruBody:getHandCount() < 1 then
    return false
  end
  local hand = kuruBody:getHandData(0)

  if hand:isFingerIndex() then
    local pointX = 720 * (hand:getKeyPoint(0).x + 1.0) / 2.0
    local pointY = 1280 * (hand:getKeyPoint(0).y + 1.0) / 2.0

    if pointY > 450 and pointY < 600 then
      if pointX > 100 and pointX < 250 and g_count == 1 and AniPlay == false then
        buttonEndNodes = createNode(scene, buttonConfigEnd)
        buttonEndNodes[1]:setEnabled(false)
        buttonEndNodes[2]:setEnabled(false)
        buttonEndNodes[3]:setEnabled(false)

        buttonEndNodes[1]:setEnabled(true)
        buttonBeginNodes[1]:setEnabled(false)
        AniPlay = true
        isBreakEffect = true
        print("kuru  first")
      elseif pointX > 350 and pointX < 450 and g_count == 2 and AniPlay == false then
        buttonEndNodes = createNode(scene, buttonConfigEnd)
        buttonEndNodes[1]:setEnabled(false)
        buttonEndNodes[2]:setEnabled(false)
        buttonEndNodes[3]:setEnabled(false)
        buttonEndNodes[2]:setEnabled(true)
        buttonBeginNodes[2]:setEnabled(false)
        AniPlay = true
        isBreakEffect = true

        print("kuru  second")
      elseif pointX > 550 and pointX < 700 and g_count == 3 and AniPlay == false then
        buttonEndNodes = createNode(scene, buttonConfigEnd)
        buttonEndNodes[1]:setEnabled(false)
        buttonEndNodes[2]:setEnabled(false)
        buttonEndNodes[3]:setEnabled(false)
        buttonEndNodes[3]:setEnabled(true)
        buttonBeginNodes[3]:setEnabled(false)
        AniPlay = true
        isBreakEffect = true

        print("kuru  thrid")
        return true
      end
    end
  end
  return false
end

--call when reset scene,e.g switch to rear camera
function reset(scene)
  faceContour = 0.0
  cheek = 0.0
  lip = 0.0
  colorLens = 0.0
  eyeBrow = 0.0
  eyeShadow = 0.0
  eyeLiner = 0.0
  eyeLashes = 0.0
  --Lut Filter
  LUT_NAME = "lut.png"
  lutStrength = 0
  applyOnlyFilter = false

  g_time = 0
  g_AniTime = 0
  g_count = 1
  AniPlay = false
  -- buttoninit = false
  isBreakEffect = false
  eyeNodes[1]:setEnabled(false)
  eyeNodes[2]:setEnabled(false)
  buttonBeginNodes[1]:setEnabled(true)
  buttonBeginNodes[2]:setEnabled(true)
  buttonBeginNodes[3]:setEnabled(true)
  buttonEndNodes[1]:setEnabled(false)
  buttonEndNodes[2]:setEnabled(false)
  buttonEndNodes[3]:setEnabled(false)
end

--call when scene close
function finalize(scene)
  kuruTouch:getTouchDownEvent():removeEventHandler(onTouchDown)
end

function changeParamEye()
  --메이크업탭 순서대로
  faceContour = 0.0
  cheek = 0.0
  lip = 0.0
  colorLens = 0.17
  eyeBrow = 0.23
  eyeShadow = 0.35
  eyeLiner = 0.2
  eyeLashes = 0.28
  --Lut Filter
  LUT_NAME = "lut.png"
  lutStrength = 0
  applyOnlyFilter = false
end

function changeParamBlush()
  --메이크업탭 순서대로
  faceContour = 0.5
  cheek = 0.55
  lip = 0.0
  colorLens = 0.17
  eyeBrow = 0.23
  eyeShadow = 0.35
  eyeLiner = 0.2
  eyeLashes = 0.28
  --Lut Filter
  LUT_NAME = "lut.png"
  lutStrength = 0
  applyOnlyFilter = false
end
function changeParamLip()
  faceContour = 0.5
  cheek = 0.55
  lip = 0.68
  colorLens = 0.17
  eyeBrow = 0.23
  eyeShadow = 0.35
  eyeLiner = 0.2
  eyeLashes = 0.28
  --Lut Filter
  LUT_NAME = "lut.png"
  lutStrength = 0
  applyOnlyFilter = false
end

--call when touch screen
function onTouchDown(event)
  print("touchdown")
end

function addNodeAndRelease(scene, node)
  scene:addNode(node)
  node:release()
  return node
end

function addChildAndRelease(parent, child)
  parent:addChild(child)
  child:release()
  return child
end
